package com.example.withroadlogistics.weibo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.withroadlogistics.Adapter.Adapter_Weibo;
import com.example.withroadlogistics.R;
import com.example.withroadlogistics.model.Blog;
import com.example.withroadlogistics.model.VBlogUser;
import com.example.withroadlogistics.until.HttpCallbackListener;
import com.example.withroadlogistics.until.HttpUtil;
import com.example.withroadlogistics.until.MySharedPreferences;
import com.example.withroadlogistics.until.constant;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class weibosend extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "ifu25";
    //定义控件
    private EditText wbcontent,wbnote;
    private Button wbsend,wbclear;

    //获取用户发表的微博列表
    private ListView mListView;
    private List<VBlogUser> mList = new ArrayList<>();

    private String originAddress = constant.url+"blog/addblog";
    //    Handler是Android SDK来处理异步消息的核心类。
//    子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";

            if ("OK".equals(msg.obj.toString())){
                result = "success";
            }else if ("Wrong".equals(msg.obj.toString())){
                result = "fail";
            }else {
                String data = msg.obj.toString();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                    if (code.equals("0")) {
                        //web端返回的json code data
                        Log.i(TAG, "handleMessage: wen端返回的json"+code+data+result);
                        //通过Bundle封装数据
                        Bundle bundle = new Bundle();
                        // bundle.putString("data", result);//data是通过后台返回数值进行判断，弹窗
                        //通过Intent控制Activity跳转
                        Toast.makeText(weibosend.this, "发送成功", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();
                        intent.setClass(weibosend.this, weibosend.class);//成功跳转
                        intent.putExtras(bundle);
                        finish();
                        startActivity(intent);
                    }else {
                        Toast.makeText(weibosend.this, result, Toast.LENGTH_LONG).show();//失败提示
                        Toast.makeText(weibosend.this, "发送失败，请重新编辑发送", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(weibosend.this, "系统异常请重试", Toast.LENGTH_LONG).show();
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weibosend);
        mListView = findViewById(R.id.mListView);//将mlistvie控件实例
        initView();
        initEvent();

        //通过MySharedPreferences类里定义好的存取方法，获取保存在里面的数据
//        String userid = (String) MySharedPreferences.getUserid(weibosend.this);
//        String pwd = (String) MySharedPreferences.getPswd(weibosend.this);
//
//        //将数据放到 TextView 展示出来
//        Toast.makeText(weibosend.this, "保存成功！"+userid+pwd, Toast.LENGTH_SHORT).show();
    }

    //按钮实例化
    private void initEvent() {
     wbsend.setOnClickListener(this);
     wbclear.setOnClickListener(this);

    }

    //实例化控件
    private void initView() {
        wbcontent =findViewById(R.id.wb_content);
        wbnote =findViewById(R.id.wb_note);
        wbsend=findViewById(R.id.wb_send);
        wbclear=findViewById(R.id.wb_clear);
    }

    private boolean isInputValid() {
        //检查用户输入的合法性，这里暂且默认用户输入合法
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wb_send:
                //发送
                register();
                break;
            case R.id.wb_clear:
                //清空
                clear();
                break;
        }
    }

    //微博发送
    private void register() {
        //取得用户输入的账号和密码
        if (!isInputValid()){
            return;
        }

        String userid = (String) MySharedPreferences.getUserid(weibosend.this);
        String contents = wbcontent.getText().toString().trim();
        String blognote = wbnote.getText().toString().trim();

        if (contents.isEmpty()) {
            Toast.makeText(weibosend.this, "微博内容不能为空！", Toast.LENGTH_LONG).show();
            return;
        }
        else if (userid.isEmpty()) {
            Toast.makeText(weibosend.this, "当前用户名无效！", Toast.LENGTH_LONG).show();
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Blog.USERID, userid);
        params.put(Blog.CONTETS, contents);
        params.put(Blog.BLOGNOTE, blognote);


        try {
            String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);
            HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Message message = new Message();
                    message.obj = response;
                    mHandler.sendMessage(message);
                }

                @Override
                public void onError(Exception e) {
                    Message message = new Message();
                    message.obj = e.toString();
                    mHandler.sendMessage(message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clear(){
        wbcontent.setText("");
    }


    public void onWindowFocusChanged(boolean hasFocus)
    {
        /**
         * 请求数据
         * 解析json
         * 适配器
         * 绑值显示
         */
        if (hasFocus){
            //访问本地接口，用10.0.2.2取代localhost
             String userid = (String) MySharedPreferences.getUserid(weibosend.this);
             String url = constant.url+"blog/getbloglist?userid="+userid;

            RxVolley.get(url, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                   // Toast.makeText(weibosend.this,t,Toast.LENGTH_LONG).show();

                    //控制台输出Json
                  //  Log.d("aaaa",""+t);

                    //解析json
                    parsingJson(t);


                    Adapter_Weibo adapter = new Adapter_Weibo(weibosend.this,mList);

                    mListView.setAdapter(adapter);


                }
            });
        }
    }

    //数据解析
    public void parsingJson(String t){
        try {

            JSONObject jsonObject = new JSONObject(t);
            JSONArray jsonList = jsonObject.getJSONArray("data");
            for(int i=0;i<jsonList.length();i++){


                JSONObject json = jsonList.getJSONObject(i);
                int id=Integer.parseInt(json.getString("id"));
                String userid=json.getString("userid");
                String contents=json.getString("contents");
                String releasetime=json.getString("releasetime");
                String blogid=json.getString("blogid");
                String blognote=json.getString("blognote");
                String username=json.getString("username");
                String realname=json.getString("realname");
                int roleid=Integer.parseInt(json.getString("roleid"));
                String pwd=json.getString("pwd");
                String phone=json.getString("phone");
                int status=Integer.parseInt(json.getString("status"));
                int photoid=Integer.parseInt(json.getString("photoid"));
                String lastlogindate=json.getString("lastlogindate");
                String createtime=json.getString("createtime");
                String loginstatus=json.getString("loginstatus");

                    //要将model定义的成员全部写出
                mList.add(new VBlogUser(id,userid,contents,releasetime,blogid,blognote,username,realname,roleid,pwd,phone,status,photoid,lastlogindate,createtime,loginstatus));

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
